package com.central.apps.handler.project;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 处理项目结项业务逻辑
 *
 * @author lidachao
 * @date 2022/9/28
 */
@Component
@Slf4j
public class ProjectCloseHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if("complete".equals(flowNode.getId()) && op.isFlag()) {
            // 查询进度申报信息
            List<Map<String, Object>> sfList = handlerService.findBySql("select proid from gq_proclose where id = " + id);
            Map<String, Object> sfMap = sfList.get(0);
            Integer proid = (Integer) sfMap.get("proid");

            // 查询项目结束日期
            List<Map<String, Object>> proList = handlerService.findBySql("select enddate from gq_proaccount where id = " + proid);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date endDate = dateFormat.parse(MapUtils.getString(proList.get(0), "enddate"));
            Date date = new Date();

            StringBuilder sql = new StringBuilder();
            sql.append("update gq_proaccount set prostatus = '已完成'");

            // 判断是否提前完工
            if (date.before(endDate)) {
                sql.append(", proschedulestatus = '提前完工'");
            }

            sql.append(" where id = ").append(proid);

            // 更新项目状态
            handlerService.updateBySql(sql.toString());
        }

        return null;
    }
}
